package com.xz.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.entity.Category;
import com.xz.entity.vo.CategoryData;
import com.xz.exceptionhandler.BaseException;
import com.xz.service.CategoryService;

public class CategoryExcelListener extends AnalysisEventListener<CategoryData> {
    public CategoryService categoryService;
    public CategoryExcelListener() {}
    public CategoryExcelListener(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
    @Override
    public void invoke(CategoryData data, AnalysisContext context) {
        if(data == null) {
            throw new BaseException(20001,"文件数据为空");
        }

        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        //判断一级分类是否重复
        Category existOneSubject = this.existOneSubject(categoryService, data.getOneCategoryName());
        if(existOneSubject == null) { //没有相同一级分类，进行添加
            existOneSubject = new Category();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle( data.getOneCategoryName());//一级分类名称
            categoryService.save(existOneSubject);
        }

        //获取一级分类id值
        String pid = existOneSubject.getId();

        //添加二级分类
        //判断二级分类是否重复
        Category existTwoSubject = this.existTwoSubject(categoryService, data.getTwoCategoryName(), pid);
        if(existTwoSubject == null) {
            existTwoSubject = new Category();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(data.getTwoCategoryName());//二级分类名称
            categoryService.save(existTwoSubject);
        }
    }

    //判断一级分类不能重复添加
    private Category existOneSubject(CategoryService categoryService, String name) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        Category oneSubject = categoryService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private Category existTwoSubject(CategoryService categoryService,String name,String pid) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        Category twoSubject = categoryService.getOne(wrapper);
        return twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
